<!-- 基础信息-业务设置 -->
<template>
  <div class="basicInfo w-100% h-100%">
    <div class="w-100% h-100%">
      <div class="mb-10px">
        <el-form
          label-width="100px"
          label-position="top"
          ref="formRef"
          :model="form"
          :rules="rules"
        >
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">业务设置</span>
                  <span class="text-#8F8F8F text-xs">（设置基本信息）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24">
                  <el-col :span="6" v-for="(item, index) in formColumns1" :key="index">
                    <el-form-item :label="item.label" :prop="item.code">
                      <el-tree-select
                        v-if="item.type === 'treeSelect' && item.code === 'deptId'"
                        v-model="form[item.code]"
                        :data="proDeptList"
                        :props="defaultProps"
                        check-strictly
                        node-key="id"
                        placeholder="请选择部门"
                        @focus="treeSelectFocus"
                        @change="treeSelectChange"
                      />

                      <el-input
                        v-if="item.type === 'input'"
                        v-model="form[item.code]"
                        placeholder="请输入"
                      />
                      <el-select
                        v-if="item.type === 'select'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                        @focus="focusGlobeState(item.code)"
                        @change="changeGlobeState(item.code, $event)"
                      >
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                      <div v-if="item.type ==='adressSelect'" style="width: 100%;">
                        <AdressSelect :salesRegion="salesRegion" @update:focus="adressFocus" @update:change="adressChange" />
                      </div>
                      <el-select
                        v-if="item.type === 'selectMultiple' && item.code === 'websiteId'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                        multiple
                        @change="changeGlobeState(item.code, $event)"
                        >
                        <!-- @focus="focusGlobeState(item.code, $event)" -->
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <p class="text-[12px] text-#8F8F8F">
                  比如输入
                  <span class="text-[#3721FF]">nike</span>
                  ，您的商品地址为
                  <span class="text-[#3721FF]">www.域名.com/nike</span>
                </p>
              </div>
            </div>
          </ContentWrap>
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">基本设置</span>
                  <span class="text-#8F8F8F text-xs">（商品基本信息）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="商品标题（外部）" prop="titleExternal">
                      <el-input
                        v-model="form.titleExternal"
                        maxlength="50"
                        type="text"
                        show-word-limit
                        placeholder="请输入"
                      />
                    </el-form-item>
                  </el-col>
                 
                </el-row>
              
                <el-row :gutter="24">
                  <el-col :span="6">
                   <el-form-item label="商品标题（内部）" prop="title">
                     <el-input
                       v-model="form.title"
                       type="text"
                       placeholder="请输入"
                       @change="titleChange"
                     />
                   </el-form-item>
                 </el-col>
                  <el-col v-for="(item, index) in formColumns2" :key="index" :span="6">
                    <el-form-item :label="item.label" :prop="item.code">
                      <el-tree-select
                        v-if="item.type === 'treeSelect' && item.code === 'categoryId'"
                        v-model="form[item.code]"
                        :data="categoryList"
                        ref="treeSelectRef"
                        :props="defaultProps"
                        check-strictly
                        node-key="id"
                        value-key="id"
                        placeholder="请选择分类"
                        clearable
                        @change="categoryChange"
                      />
                      <el-input
                        v-if="item.type === 'input'"
                        v-model="form[item.code]"
                        placeholder="请输入"
                      />
                      <el-select
                        v-if="item.type === 'select'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                      >
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                      <div v-if="item.type === 'switch'">
                        <el-switch
                          v-model="form[item.code]"
                          :active-value="1"
                          :inactive-value="0"
                          @change="tagFlagChange(form[item.code])"
                        />
                        <div class="flex flex-col items-center ">
                          <template v-for="(it, idx) in tagFlagListMap">
                            <div v-if="form[item.code] == 1" class="flex items-center mt-2" :key="idx">
                               <el-input
                                v-model="it.value"
                                placeholder="请输入"
                                @input="inputPurchaseListMap"
                              />
                              <p class="flex inline-block">
                                <Icon @click="addtagFlag" icon="ant-design:plus-circle-outlined" class="text-#8F8F8F ml-2 cursor-pointer"  />
                                <Icon @click="deletetagFlag(idx)" icon="material-symbols:cancel-outline" class="text-#8F8F8F ml-2 cursor-pointer" />
                              </p>
                            </div>
                          </template>
                        </div>
                      </div>

                    </el-form-item>
                  </el-col>
                </el-row>
                <p class="text-[12px] text-#8F8F8F mb-24px">
                  开启商品标签，则同意平台为您所创建商品，在商详里展示“标签”板块
                </p>
                <el-row :gutter="24">
                  <el-col :span="16">
                    <el-form-item prop="purchaseList">
                      <template #label>
                        <span>采购链接</span>
                        <div class="mt-2">
                          <el-button
                            type="text"
                            color="#3721FF"
                            plain
                            link
                            class="mb-4px"
                            @click="addPurchaseLink"
                          >
                            + 添加采购链接
                          </el-button>
                        </div>
                      </template>
                      <div>
                        <template v-for="(itm, idx) in purchaseListMap" :key="idx">
                          <div class="flex w-700px">
                            <el-input
                              v-model="itm.url"
                              class="mb-4px"
                              placeholder="请输入"
                              @input="inputPurchaseListMap"
                              />
                            <el-input
                              v-model="itm.remark"
                              class="ml-2 mb-4px"
                              placeholder="备注"
                              @input="inputPurchaseListMap"
                              />
                            <Icon icon="material-symbols:cancel-outline" class="text-#8F8F8F ml-2 cursor-pointer" @click="removePurchaseLink(idx)" />
                          </div>
                        </template>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </ContentWrap>
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">模板设置</span>
                  <span class="text-#8F8F8F text-xs">（设置客户展示效果）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item prop="template" label-position="left">
                      <template #label>
                        <p>模板选择</p>
                      </template>
                      <el-button
                        color="#3721FF"
                        type="primary"
                        class="mb-4px"
                        @click="handleSelectTemplate"
                      >
                        <Icon icon="ant-design:plus-outlined" />
                        请选择
                      </el-button>
                      <div v-if="selectedTemplateResMap">
                        <div class="flex flex-col items-center ml-4">
                          <!-- <img
                            class="w-50px h-50px rounded-6px"
                            :src="selectedTemplateResMap.previewPicUrls"
                            alt=""
                          /> -->
                          <el-button plain color="#3721FF" class="text-[12px] text-#1A2029">{{
                            selectedTemplateResMap.name
                          }}</el-button>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col v-for="(item, index) in formColumns3" :key="index" :span="6">
                    <el-form-item :label="item.label" :prop="item.code">
                      <el-input
                        v-if="item.type === 'input'"
                        v-model="form[item.code]"
                        placeholder="请输入"
                      />
                      <el-select
                        v-if="item.type === 'select'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                        @change="handleSelectChange(form[item.code], item.code)"
                      >
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                      <el-switch
                        v-if="item.type === 'switch'"
                        v-model="form[item.code]"
                        :active-value="1"
                        :inactive-value="0"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="9">
                    <el-form-item label="是否赠送优惠券">
                      <el-switch
                        v-model="isCouponAmount"
                        active-text="开启"
                        :active-value="1"
                        :inactive-value="0"
                      />
                      <div class="flex items-center justify-between ml-40px" v-if="isCouponAmount">
                        <span class="inline-block w-[200px] text-[14px] text-right mr-[10px]"
                          >优惠券赠送金额</span
                        >
                        <el-input
                          class="w-[50px]"
                          v-model="form.couponAmount"
                          placeholder="请输入"
                        />
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <div class="flex ml-10px mt-40px w-[100%] justify-around">
                    <div class="w-[50%] flex">
                      <p class="w-[10%]">联系方式</p>
                      <div class="w-[80%]">
                        <TableForm
                          @update:form-data="updateTableForm"
                          ref="tableFormRef"
                          :form-data-edit="formData"
                          :online-service="form.onlineService"
                        />
                      </div>
                    </div>
                    <div class="w-[50%]">
                      <div class="w-[100%] flex">
                        <p class="w-[14%]">表单填写设置</p>
                        <div class="w-[70%]">
                          <TableSet
                            ref="tableSetRef"
                            @update:table-data="updateTableSet"
                            :form-data-edit="formData"
                          />
                        </div>
                      </div>
                      <div class="mt-10px">
                        <span> 主页是否显示 </span>
                        <el-switch
                          v-model="form.homepageFlag"
                          :active-text="form.homepageFlag ? '开启' : '关闭'"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </div>
                    </div>
                  </div>
                </el-row>
              </div>
            </div>
          </ContentWrap>
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">物流设置</span>
                  <span class="text-#8F8F8F text-xs">（设置物流方式）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="物流方式" :rules="logisticsRules" prop="logisticsMethods">
                      <template #label>
                        <p>物流方式<span class="text-red-600">*</span></p>
                      </template>
                      <el-checkbox-group v-model="logisticsMethods" @click="logisticsChange">
                        <template v-for="(itm, idx) in logisticsMethodList" :key="idx">
                          <el-checkbox :label="itm.value" border>
                            <span>{{ itm.label }}</span>
                          </el-checkbox>
                        </template>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col v-for="(item, index) in formColumns4" :key="index" :span="6">
                    <el-form-item :label="item.label" :prop="item.code">
                      <el-input
                        v-if="item.type === 'inputNumber'"
                        v-model="form[item.code]"
                        type="number"
                        placeholder="请输入"
                      />
                      <el-input
                        v-if="item.type === 'input'"
                        v-model="form[item.code]"
                        placeholder="请输入"
                      />
                      <el-select
                        v-if="item.type === 'select'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                      >
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                      <el-switch
                        v-if="item.type === 'switch'"
                        v-model="form[item.code]"
                        :active-value="1"
                        :inactive-value="0"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <p class="text-[12px] text-#8F8F8F mb-24px">
                  注：套餐运费优先级：偏远地区>套餐运费，只生效一个；商品运费：偏远地区邮费>运费，只生效一个。如果开启套餐，请在套餐处设置运费
                </p>
              </div>
            </div>
          </ContentWrap>
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">广告设置</span>
                  <span class="text-#8F8F8F text-xs">（设置广告像素和ab跳）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24">
                  <el-col v-for="(item, index) in formColumns5" :key="index" :span="6">
                    <el-form-item :label="item.label" :prop="item.code">
                      <el-input
                        v-if="item.type === 'input'"
                        v-model="form[item.code]"
                        placeholder="请输入"
                      />
                      <el-select
                        v-if="item.type === 'select'"
                        placeholder="请选择"
                        v-model="form[item.code]"
                      >
                        <el-option
                          v-for="itm in item.options"
                          :key="itm.value"
                          :label="itm.label"
                          :value="itm.value"
                        />
                      </el-select>
                      <el-switch
                        v-if="item.type === 'switch'"
                        v-model="form[item.code]"
                        :active-value="1"
                        :inactive-value="0"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24" v-if="props.type != 3">
                  <el-col :span="12">
                    <el-form-item label="b商品详情">
                      <el-button type="primary" color="#3721FF" @click="showSelectProducts">
                        + 选择商品</el-button
                      >
                      <div
                        v-if="form.productName && form.productName.length > 0"
                        class="flex flex-wrap mt-4"
                      >
                        <div
                          class="flex flex-col items-center ml-4"
                          v-for="(item, index) in form.productName"
                          :key="index"
                        >
                          <img class="w-50px h-50px rounded-6px" :src="item.cover" alt="" />
                          <span class="text-[12px] text-#1A2029">{{ item.title }}</span>
                          <Icon icon="material-symbols:cancel-outline" class="text-#8F8F8F cursor-pointer" @click="removeProductName(index)" />
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </ContentWrap>
          <ContentWrap :show-border="false">
            <div>
              <div class="bg-#F7F7FB p-10px rounded-6px">
                <p class="set-title">
                  <span class="font-semibold">图文信息</span>
                  <span class="text-#8F8F8F text-xs">（设置展示内容）</span>
                </p>
              </div>
              <div class="mt-4">
                <el-row :gutter="24" v-for="(item, index) in formColumns6" :key="index">
                  <el-col :span="item.type === 'editor' ? 20 : 6">
                    <el-form-item :label="item.label" :prop="item.code">
                      <div class="flex" v-if="item.type === 'upload'">
                        <UploadImg
                          v-model="form[item.code]"
                          draggable="false"
                          height="80px"
                          width="80px"
                          class="min-w-80px"
                          @change="titleChange"
                        />
                      </div>
                      <div class="flex" v-if="item.type === 'uploads'">
                        <UploadImgs
                          v-model="form[item.code]"
                          draggable="false"
                          height="80px"
                          width="80px"
                          class="min-w-80px"
                        />
                      </div>
                      <div v-if="item.type === 'editor'">
                        <Editor v-model="form[item.code]" height="600px" class="mt-10px" />
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </ContentWrap>
        </el-form>
        <!-- <ContentWrap :show-border="false">
          <div class="w-[100%] h-[100%] el-dia-btn text-center">
            <el-button type="default" @click="$router.go(-1)">取消</el-button>
            <el-button type="primary" color="#3721FF" @click="submit">保存</el-button>
            <el-button type="primary" color="#3721FF">完成并预览</el-button>
          </div>
        </ContentWrap> -->
      </div>
    </div>
    <SelectProducts
      ref="selectProductsRef"
      :showDot="true"
      width="50%"
      title="选择商品"
      @confirm="confirmSelectProducts"
      :type="2"
    />
    <SelectTemplate
      ref="selectTemplateRef"
      :showDot="true"
      templateType="2"
      width="60%"
      title="选择模板"
      @update:select-template="updateSelectTemplate"
      @selected-template-res="selectedTemplateRes"
      :form-data="form"
    />
  </div>
</template>

<script setup lang="ts">
import TableForm from './tableForm.vue'
import TableSet from './tableSet.vue'
import { ProductApi } from '@/api/product/addProduct'
import { getDictDataPage } from '@/api/system/dict/dict.data'
import { getCategoryList } from '@/api/publicInterf/index'
import { getGlobeState, getGlobeStateByIdList } from '@/api/publicInterf/index.ts'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { rules, ProductVO } from '@/api/product/addProduct/index.ts'
import SelectTemplate from '../selectTemplate/index.vue'
import AdressSelect from '@/components/AdressSelect/index.vue'
import { deepCopy } from '@/utils'
const treeSelectRef = ref()
const categoryList = ref()
const selectProductsRef = ref()
const formRef = ref()
const tableFormRef = ref() // 联系方式
const tableSetRef = ref() //表单填写设置
const selectTemplateRef = ref()
const proDeptList = ref()
const selectedTemplateResMap = ref()
const tagFlagListMap = ref([
  {
    value:''
  }
]) //标签列表
const templateList = ref([])
const salesRegion = ref([]) // 地区
const languageList = ref([]) //语言
const listByDeptList = ref([]) //user列表
const logisticsMethodList = ref([]) //物流方式
const logisticsMethods = ref([]) //物流方式
const simpleList = ref([]) //网站列表
const policySimpleList = ref([]) //底部政策列表
const rollUserPageList = ref([]) //滚动购买列表
const isCouponAmount = ref(false) //是否为优惠券金额
const emit = defineEmits(['update:form', 'update:contactInfo'])
const props = defineProps(['formData', 'type'])
const purchaseListMap = ref([
  {
    url: '',
    remark:''
  }
])
const form = ref<ProductVO>({
  tagFlag: 0,
  template: '',
  templateName: '',
  homepageFlag: 0, //是否首页推荐
  logisticsMethod: '', //物流方式
  commodityId: '', //B商家id
  productName: [], //B商家json
  tagValue: '', //标签
  websiteId: [], //网站
  domain:[], //域名
})
// 获取滚动购买列表
const handleRollUserPage = async () => {
  await ProductApi.rollPage({ pageNo: 1, pageSize: 100 }).then((res) => {
    if (res?.list.length > 0) {
      rollUserPageList.value = res?.list.map((item) => ({
        label: item.categoryName,
        value: item.id
      }))
    }
  })
}
const removeProductName = (idx) => {
  form.value.productName.splice(idx, 1)
  form.value.commodityId = form.value.productName?.map((item) => item.id).join(',')|| ''
}
const logisticsChange = (val) => {
  console.log(logisticsMethods.value,'logisticsMethods6666')
}
// 在线客服
const handleSelectChange = (val, vls) => {
  switch (vls) {
    case 'onlineService':
      tableFormRef.value?.getRequired(val)
  }
}
// 
const removePurchaseLink = (idx) => {
  purchaseListMap.value.splice(idx, 1)
  form.value.purchaseList = purchaseListMap.value
}
// 获取底部政策列表
const handlePolicySimpleList = async () => {
  await ProductApi.policySimpleList().then((res) => {
    policySimpleList.value = res.map((item) => ({
      label: item.name,
      value: item.id
    }))
  })
}
// 获取网站
const handleSimpleList = async () => {
  await ProductApi.simpleList().then((res) => {
    simpleList.value = res.map((item) => ({
      label: item.name,
      value: item.id,
      domain: item.domain
    }))

  })
}
const tagFlagChange = (val) => {

  if (val == 1) {
    console.log(tagFlagListMap,'tagFlagListMap');
    if(tagFlagListMap.value.length == 0) {
      tagFlagListMap.value.push({
        value:''
      })
    }else{
      form.value.tagValue = tagFlagListMap.value.map((item) => item.value).join(',')
    }
  } else {
    form.value.tagValue = ''
  }
}
const addtagFlag = () => {
  if(tagFlagListMap.value.length == 10) {
    ElMessage.error('最多添加10个标签')
    return
  }
  tagFlagListMap.value.push({
    value:''
  })
}
const deletetagFlag = (idx) => {
  if(tagFlagListMap.value.length == 1) {
       ElMessage.error('至少保留一个标签')
    return
  }
  tagFlagListMap.value.splice(idx, 1)
}
const selectedNode = computed(() => {
  const findNode = (data, targetId) => {
    for (const item of data) {
      if (item.id === targetId) return item
      if (item.children) {
        const found = findNode(item.children, targetId)
        if (found) return found
      }
    }
    return null
  }
  return findNode(categoryList.value, form.value.categoryId)
})
const categoryChange = (val) => {
  const selectedNodes = selectedNode.value
  form.value.categoryId = selectedNodes?.id
  form.value.categoryName = selectedNodes?.name
}
//获取部门列表(中文)
const selectedDeptNode = computed(() => {
  const findNode = (data, targetId) => {
    for (const item of data) {
      if (item.id === targetId) return item
      if (item.children) {
        const found = findNode(item.children, targetId)
        if (found) return found
      }
    }
    return null
  }
  return findNode(proDeptList.value, form.value.deptId)
})
//获取部门列表
const treeSelectChange = async (val) => {
  form.value.userId = ''
  await handleGetUserList(val)
  const selectedDeptNodes = selectedDeptNode.value
  form.value.deptId = selectedDeptNodes?.id
  form.value.deptName = selectedDeptNodes?.name
  console.log(form.value,'form.value');
}
// 根据部门ID获取用户下拉列表
const handleGetUserList = async (id) => {
  await ProductApi.listByDept({ deptId: id }).then((res) => {
    listByDeptList.value = res.map((item) => ({
      label: item.nickname,
      value: item.id
    }))
  })
}
const handleGetCategory = async () => {
  const res = await getCategoryList()
  categoryList.value = handleTree(res)
}
// 获取物流方式字典
const getLogisticsMethod = async (val) => {
  logisticsMethodList.value = []
  try {
   await ProductApi.getGlobeStateMethod({
      pageNo: 1,
      pageSize: 10,
      stateId: val
    }).then((res) => {
      logisticsMethodList.value = res.list.map((item) => ({
        label: item.methodName,
        value: item.id
      }))
      if (val && res?.list.length == 0) {
        ElMessage.error('该地区暂无物流方式, 请前往维护！')
        return
      }
      // 判断logisticsMethodList.value里面有没有宅配到府210017这个id，有就默认选中      
      if(logisticsMethods.value.length == 0){
        logisticsMethodList.value.forEach((item) => {
          if(item.value == 210017){
            logisticsMethods.value.push(item.value)
          }
        })
      }
      //  if(props.formData.id=='' && logisticsMethods.value.length==0){
      //   logisticsMethods.value.push(210017)
      // }
    })
  } catch (error) {
    console.log(error)
  }
}
// 
// const inputTagFlagListMap = (val) => {
//   emit('update:form', form.value)
// }
// 采购链接
const inputPurchaseListMap = (val) => {
  form.value.purchaseList = purchaseListMap.value.filter((item) => item.url!== '')
  form.value.tagValue = tagFlagListMap.value.length>0?tagFlagListMap.value.map((item) => item.value).join(','):''
  form.value.logisticsMethod = logisticsMethods.value.length>0 ? logisticsMethods.value.join(',') : ''
  emit('update:form', form.value)
}
const titleChange = (val) => {
  console.log(form.value,'form.value99999')
  emit('update:form', form.value)
}
// 选择
const changeGlobeState = (val, res) => {
  if (val == 'language') {
    localStorage.setItem('language', res)
  }
  if (val == 'userId') {
    listByDeptList.value.forEach((item) => {
      if (item.value == res) {
        form.value.userId = item.value
        form.value.userName = item.label
      }
    })
  }
  if (val == 'areaId') {
    // 清空语言
    form.value.language = ''
    salesRegion.value.forEach((item) => {
      if (item.value == res) {
        form.value.areaId = item.value
        form.value.areaName = item.label
      }
    })
    // 调取物流接口
    getLogisticsMethod(res)
  }

  if (val == 'websiteId') {
    let mywebsiteId = []
    let mywebsiteName = []
    let myDomain = []
    simpleList.value.forEach((item) => {
      res.forEach((item1) => {
        if (item.value == item1) {
          console.log('res', res);
          mywebsiteId.push(item.value)
          form.value.websiteId = mywebsiteId
          mywebsiteName.push(item.label)
          form.value.websiteName = mywebsiteName
           console.log('form.value.websiteName', form.value.websiteName);
          myDomain.push(item.domain)
          form.value.domain = myDomain
        }
      })
    })
  }
}
const adressFocus = (val) => {
    handleGetGlobeState()
}
const adressChange = (val) => { 
  if (val) {
    // 清空语言
    form.value.language = ''
    salesRegion.value.forEach((item) => {
      if (item.value == val) {
        form.value.areaId = item.value
        form.value.areaName = item.label
      }
    })
    // 调取物流接口
    getLogisticsMethod(val)
    handleGetGlobeStateByIdList(val)
  }
}
// 获取下拉列表
const focusGlobeState = (val) => {
  switch (val) {
    // case 'areaId': // 地区
    //   handleGetGlobeState()
    //   break
    case 'language': //语言
      if (!form.value.areaId) {
        ElMessage.warning('请先选择地区')
        return
      }
      handleGetGlobeStateByIdList(form.value.areaId)
      break
    case 'userId': //用户
      if (!form.value.deptId) {
        ElMessage.warning('请先选择部门')
        return
      }
  }
}
// 地区
const handleGetGlobeState = async () => {
  try {
    const res = await getGlobeState()
    salesRegion.value = res.map((item) => ({
      label: item.stateName,
      value: item.id
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}
// 语言

const handleGetGlobeStateByIdList = async (areaId) => {
  languageList.value = []
  try {
    const res = await getGlobeStateByIdList({ id: areaId })
    languageList.value = res.map((item) => ({
      label: item,
      value: item
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}
//获取联系方式
const contactInfo = ref([])
const updateTableForm = (val) => {
  contactInfo.value = val
  emit('update:contactInfo', val)
  const obj = {}
  val.forEach((item) => {
    obj[item.platform] = item.value
  })
  let tableForm = obj
  form.value = { ...form.value, ...tableForm }
  form.value.logisticsMethod = logisticsMethods.value.length>0 ? logisticsMethods.value.join(',') : ''
  emit('update:form', form.value)
}
const updateTableSet = (val) => {
  let tableSet = {}
  val.map((item) => {
    switch (item.field) {
      case '邮箱':
        tableSet.emailShow = item.show ? 1 : 0
        tableSet.emailFlag = item.required ? 1 : 0
      case '邮编':
        tableSet.zipCodeShow = item.show ? 1 : 0
        tableSet.zipCodeFlag = item.required ? 1 : 0
      case '门牌号/建筑物名':
        tableSet.houseNumberShow = item.show ? 1 : 0
        tableSet.houseNumberFlag = item.required ? 1 : 0
      case 'Whatsapp':
        tableSet.whatsappShow = item.show ? 1 : 0
        tableSet.whatsappFlag = item.required ? 1 : 0
      case 'Line':
        tableSet.lineShow = item.show ? 1 : 0
        tableSet.lineFlag = item.required ? 1 : 0
    }
  })
  form.value = { ...form.value, ...tableSet }
  form.value.logisticsMethod = logisticsMethods.value.length>0 ? logisticsMethods.value.join(',') : ''
  emit('update:form', form.value)
}
// 主页是否显示
// const changeHomepageFlag = (val) => {
//   form.value.homepageFlag = form.value.homepageFlag ? 1 : 0
//   emit('update:form', form.value)
// }
// 提交页面
const submit = async () => {
  try {
    let res = await formRef.value?.validate()
    if (res) {
      // console.log('formRef.value?.validate()', res)
      // console.log(form.value)
    }
  } catch (e) {
    console.log(e)
  }
}

// 新增采购链接
const addPurchaseLink = () => {
  purchaseListMap.value.push({
    url: '',
    remark: ''
  })
}
const showSelectProducts = () => {
  selectProductsRef.value?.show()
}

const treeSelectFocus = async () => {
  // 清空人员
  if (!form.value.deptId) {
    return
  }
  // console.log('blur')
  await getDeptList()
}
const handleSelectTemplate = async (val) => {
  selectTemplateRef.value?.show(val)
}
//
// const selectedProductList = ref()
const confirmSelectProducts = (val) => {
  // selectedProductList.value = val
  form.value.commodityId = val?.map((item) => item.id).join(',')
  form.value.productName = val.map((item) => {
    return {
      title: item.title,
      cover: item.cover,
      id: item.id
    }
  })
  
}
// 获取模板
const updateSelectTemplate = (val) => {
  form.value.template = val
  // emit('update:form', form.value)
}
const selectedTemplateRes = (val) => {
  selectedTemplateResMap.value = val
  console.log('selectedTemplateResMap.value', selectedTemplateResMap.value);
  
  form.value.templateName = val.name
}
// 获取部门列表
const getDeptList = async () => {
  try {
    proDeptList.value = handleTree(await DeptApi.getSimpleDeptList())
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}
onMounted(async () => {
  getTemplateList()
  await getDeptList()
  handleGetGlobeState()
  handlePolicySimpleList()
  await handleSimpleList()
  handleGetCategory()
  await handleRollUserPage()
  simpleList.value.forEach((item) => {
    form.value.websiteId.forEach((item1) => {
      if (item.value == item1) {
        form.value.domain = item.domain?.split(',')    
      }
    })
  })
  form.value.productName = (form.value.bname!='[]'&& form.value.bname!=null && form.value.bname!= undefined && form.value.bname!='')?JSON.parse(form.value.bname):[]
  await getLogisticsMethod(form.value.areaId)
 
})

// 抛出form数据
const updateSetBusiness = () => {
  form.value.logisticsMethod = logisticsMethods.value.length>0 ? logisticsMethods.value.join(',') : ''
  form.value.tagValue = tagFlagListMap.value ? tagFlagListMap.value.map((item) => item.value).join(',') : '' //标签
  return form.value
}
// 正则传递
const getValidate = async () => {
  let isValidate = false
  try {
    let res = await formRef.value?.validate()
    if (res) {
      isValidate = true
    } else {
      isValidate = false
    }
  } catch (e) {
    isValidate = false
  }
  return isValidate
}
// 获取模板列表
const getTemplateList = async () => {
  ProductApi.templatePage().then((res) => {
    templateList.value = res.list
    selectedTemplateResMap.value = templateList.value.filter((item) => item.id == form.value.template)[0]
  })
}
defineExpose({
  updateSetBusiness,
  getValidate
})
// 回显form
watch(
  () => props.formData,
  async (val) => {
    form.value = val

    await getTemplateList()
    // 调取物流接口
    // getLogisticsMethod(form.value.areaId)
    logisticsMethods.value = val.logisticsMethod?.split(',').map((item) => Number(item))
   
    if(val.tagValue){
      tagFlagListMap.value = val.tagValue?.split(',')?.map((it=>{
        return {
          value:it
        }
      }))
    }
    if(val.websiteName){
      form.value.websiteName = val.websiteName?.split(',')
    }
    if(JSON.parse(JSON.stringify(val.websiteId)) && JSON.parse(JSON.stringify(val.websiteId)).length>0){
      form.value.websiteId = val.websiteId?.split(',').map((item) => Number(item))
    }
    form.value.bottomPolicy = val.bottomPolicy ? Number(val.bottomPolicy) : ''
    selectedTemplateResMap.value = templateList.value.filter((item) => item.id == val.template)[0]    

    localStorage.setItem('language', val.language)
    if (val.picture && val.picture.length > 0) {
      if (typeof val.picture === 'string') {
        form.value.picture = val.picture?.split(',')
      } else {
        form.value.picture = val.picture
      }
    } else {
      form.value.picture = []
    }

    if (form.value.deptId) {
      await handleGetUserList(form.value.deptId)
    }
    form.value.userName = listByDeptList.value.filter(
      (item) => item.value == form.value.userId
    )[0]?.label
    let newPurchaseListMap = val?.purchaseList?.filter((item) => item?.url!='')
    purchaseListMap.value = newPurchaseListMap.map((item) => ({
      url: item.url,
      remark: item.remark
    }))
  }
)
// 业务设置
const formColumns1 = ref([
  {
    label: '部门',
    code: 'deptId',
    type: 'treeSelect'
  },
  {
    label: '销售地区',
    code: 'areaId',
    type: 'adressSelect',
    options: salesRegion
  },
  {
    label: '所属网站',
    code: 'websiteId',
    type: 'selectMultiple',
    options: simpleList
  },
  {
    label: '链接后缀',
    code: 'urlSuffix',
    type: 'input',
    required: true,
    options: [
      {
        label: '集团',
        value: '1'
      },
      {
        label: '分公司',
        value: '2'
      }
    ]
  },
  {
    label: '人员',
    code: 'userId',
    type: 'select',
    required: true,
    options: listByDeptList
  },
  {
    label: '语言',
    code: 'language',
    type: 'select',
    required: true,
    options: languageList
  }
])
// 基本设置
const formColumns2 = ref([
  // {
  //   label: '商品标题（外部）',
  //   code: 'department',
  //   type: 'select',
  //   required: true,
  //   length: 12,
  //   options: [
  //     {
  //       label: '集团',
  //       value: '1'
  //     },
  //     {
  //       label: '分公司',
  //       value: '2'
  //     }
  //   ]
  // },
  // {
  //   label: '商品标题（内部）',
  //   code: 'title',
  //   type: 'input',
  //   required: true
  // },
  {
    label: '商品分类',
    code: 'categoryId',
    type: 'treeSelect'
  },
  {
    label: '商品副标题',
    code: 'subtitle',
    type: 'input'
  },

  {
    label: '商品标题（短信）',
    code: 'titleMessage',
    type: 'input',
    required: true
  },
  {
    label: '商品标签',
    code: 'tagFlag',
    type: 'switch'
  }
])
// 模板设置
const formColumns3 = ref([
  {
    label: '底部政策',
    code: 'bottomPolicy',
    type: 'select',
    required: true,
    length: 12,
    options: policySimpleList
  },
  {
    label: '滚动购买',
    code: 'rollId',
    type: 'select',
    required: true,
    length: 12,
    options: rollUserPageList
  },
  {
    label: '倒计时',
    code: 'countdown',
    type: 'input',
    required: true
  },
  {
    label: '销售设置',
    code: 'saleCount',
    type: 'input',
    required: true
  },
  {
    label: '在线客服',
    code: 'onlineService',
    type: 'select',
    required: true,
    options: [
      {
        label: 'facebookContact',
        value: 'facebookContact'
      },
      {
        label: 'messengerContact',
        value: 'messengerContact'
      },
      {
        label: 'instagramContact',
        value: 'instagramContact'
      },
      {
        label: 'whatsappContact',
        value: 'whatsappContact'
      },
      {
        label: 'line',
        value: 'line'
      },
      {
        label: 'phone',
        value: 'phone'
      },
      {
        label: 'email',
        value: 'email'
      }
    ]
  }
])
// 物流设置
const formColumns4 = ref([
  {
    label: '运费',
    code: 'shippingFee',
    type: 'inputNumber',
    required: false,
    length: 12
  },
  {
    label: '偏远地区邮费',
    code: 'remotePostage',
    type: 'inputNumber',
    required: false
  },
  {
    label: '手续费',
    code: 'commission',
    type: 'inputNumber',
    required: false
  }
])

// 广告设置
const formColumns5 = ref([
  {
    label: 'Facebook像素ID',
    code: 'facebook',
    type: 'input',
    required: true
  },
  {
    label: 'Tik Tok像素ID',
    code: 'tiktok',
    type: 'input',
    required: true
  },
  {
    label: 'Google像素ID',
    code: 'gooogle',
    type: 'input',
    required: true
  },
  {
    label: 'snapchat像素ID',
    code: 'snapchat',
    type: 'input',
    required: false
  }
])

// 图文信息
const formColumns6 = ref([
  {
    label: '商品封面',
    code: 'cover',
    type: 'upload',
    required: true
  },
  {
    label: '商品轮播图',
    code: 'picture',
    type: 'uploads',
    required: true
  },
  {
    label: '网站图标',
    code: 'favicon',
    type: 'upload',
    required: true
  },
  {
    label: '商品详情',
    code: 'detail',
    type: 'editor',
    required: true
  }
])

// 自定义校验规则
const logisticsRules = [
  {
    validator: (rule, value, callback) => {
      if (logisticsMethods.value.length === 0) {
        callback(new Error('请至少选择一种物流方式'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }
]
</script>

<style scoped>
@import '@/styles/theme.scss';
@import '@/styles/website.scss';
</style>

<style lang="scss" scoped>
.set-title {
  border-left: 4px solid #3721ff;
  padding-left: 10px;
  font-size: 14px;
  /* font-weight: 600; */
  display: block;
  height: 14px;
  line-height: 14px;
}
.upload {
  border: 1px dashed #d9d9d9;
}
</style>
